'''struct 解决粘包现象'''
'''tcp协议实现客户端输入的命令执行、服务端返回命令执行的结果'''
import struct,json
from socket import *
import subprocess
ip_port = ("localhost", 51590)
buffer_size = 1024
back_log = 5
tcp_server=socket(AF_INET,SOCK_STREAM)
tcp_server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) #就是它，在bind前加
tcp_server.bind(ip_port)
tcp_server.listen(back_log)
while True:
    print("waiting for connect...")
    conn,addr=tcp_server.accept()
    while True:
        try:
            cmd=conn.recv(buffer_size)
            if not cmd:break
            print('cmd: %s' %cmd)
            res=subprocess.Popen(cmd.decode('utf-8'),
                                 shell=True,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            err = res.stderr.read()
            # print(err.decode("utf-8"))
            if err:
                back_msg = err
            else:
                back_msg = res.stdout.read()
            if not back_msg:
                back_msg="命令执行成功，".encode("utf-8")
            headers={'data_size':len(back_msg)}
            head_json=json.dumps(headers)
            head_json_bytes=bytes(head_json,encoding='utf-8')

            conn.send(struct.pack('i',len(head_json_bytes))) #先发报头的长度
            conn.send(head_json_bytes) #再发报头
            conn.sendall(back_msg) #在发真实的内容
        except Exception:
            print(Exception)
    conn.close()